﻿using System;

namespace IteratorPattern;
// 抽象聚合类
public interface IListCollection
{
    IIterator GetIterator();
}

// 迭代器抽象类
public interface IIterator
{
    bool MoveNext();
    Object GetCurrent();
    void Next();
    void Reset();
}

// 具体聚合类
public class ConcreteList : IListCollection
{
    readonly int[] _collection = { 2, 4, 6, 8 };

    public IIterator GetIterator()
    {
        return new ConcreteIterator(this);
    }

    public int Length => _collection.Length;

    public int GetElement(int index)
    {
        return _collection[index];
    }
}

// 具体迭代器类
public class ConcreteIterator(ConcreteList list) : IIterator
{
    // 迭代器要集合对象进行遍历操作，自然就需要引用集合对象
    private int _index;


    public bool MoveNext()
    {
        return _index < list.Length;
    }

    public Object GetCurrent()
    {
        return list.GetElement(_index);
    }

    public void Reset()
    {
        _index = 0;
    }

    public void Next()
    {
        if (_index < list.Length)
        {
            _index++;
        }
    }
}

// 客户端
public static class Program
{
    public static void Main()
    {
        IListCollection list = new ConcreteList();
        var iterator = list.GetIterator();

        while (iterator.MoveNext())
        {
            int i = (int)iterator.GetCurrent();
            Console.WriteLine(i.ToString());
            iterator.Next();
        }
        iterator.Reset();
        Console.WriteLine("iterator reset");
        Console.WriteLine((int)iterator.GetCurrent());

        Console.Read();
    }
}